package com.cloudkinto.controller.platform;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.platform.*;
import com.cloudkinto.service.platform.vo.store.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hua
 * @since 2024-12-25
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "平台店铺模块")
@RequestMapping("/api/admin/oms/PlatformStore")
public class PlatformStoreOmsController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(PlatformStoreOmsController.class);

    private final PlatformStoreService service;
    private final PlatformOrderYahooSyncService platformOrderYahooSyncOrderService;
    private final PlatformOrderAmazonSyncService platformOrderAmazonSyncService;
    private final PlatformOrderShopifySyncService platformOrderShopifySyncOrderService;
    private final PlatformOrderMakeshopSyncService platformOrderMakeshopSyncService;

    @UserSessionRequired
    @PutMapping("/update")
    @ApiOperation(value = "编辑", notes = "编辑")
    public SingleResult update(@RequestBody @Validated PlatformUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success(service.update(req, userId, getCompanyId()));
    }

    @UserSessionRequired
    @PutMapping("/ableStatus")
    @ApiOperation(value = "更新状态", notes = "更新状态")
    public SingleResult ableStatus(@RequestBody @Validated PlatformUpdateStatusReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success(service.ableStatus(req, userId, getCompanyId()));
    }


    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/updateStorePresale")
    @ApiOperation(value = "更新店铺预售状态", notes = "更新店铺预售状态")
    public SingleResult updateStorePresale(Long storeId, Integer presale) {
        service.updateStorePresale(storeId, presale, getCurrentUserId());
        return SingleResult.success();
    }


    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit();
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "site", value = "站点"),
            @ApiImplicitParam(name = "platformCode", value = "平台"),
            @ApiImplicitParam(name = "storeStatus", value = "店铺状态"),
            @ApiImplicitParam(name = "authSyncStatus", value = "授权状态"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小"),
    })
    public PageResult listPage(HttpServletRequest request) {
        Map<String, String> map = this.getMap(request);
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        map.put("current", current);
        map.put("pageSize", size);
        return service.getListPage(map);
    }


    @UserSessionRequired
    @GetMapping("/statusStatistics")
    @ApiOperation(value = "平台数量统计", notes = "平台数量统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "site", value = "站点"),
            @ApiImplicitParam(name = "platformCode", value = "平台"),
            @ApiImplicitParam(name = "storeStatus", value = "店铺状态"),
            @ApiImplicitParam(name = "authSyncStatus", value = "授权状态"),
    })
    public SingleResult statusStatistics(HttpServletRequest request) {
        Map<String, String> map = this.getMap(request);
        return SingleResult.success(service.statusStatistics(map));
    }


    public Map<String, String> getMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        map.put("keyword", keyword);
        String site = request.getParameter("site");
        map.put("site", site);
        String authSyncStatus = request.getParameter("authSyncStatus");
        map.put("authSyncStatus", authSyncStatus);
        String storeStatus = request.getParameter("storeStatus");
        String platformCode = request.getParameter("platformCode");
        map.put("storeStatus", storeStatus);
        map.put("platformCode", platformCode);
        map.put("companyId", getCompanyId() + "");
        map.put("source", StaticDict.System_Source.OMS.getValue());
        return map;
    }


    @UserSessionRequired
    @PostMapping("/getYahooAuthorizeUrl")
    @ApiOperation(value = "Yahoo 用户授权第一步， yahoo店铺新增/更新授权 掉此接口，跳转到返回的url", notes = "Yahoo 用户授权第一步， 获取授权url，前端直接跳转到该页面")
    public SingleResult getYahooAuthorizeUrl(@RequestBody @Validated StoreYahooAddReq req) {
        return SingleResult.success(platformOrderYahooSyncOrderService.getYahooAuthorizeUrl(req, getCurrentUserId(), getCompanyId()));
    }

    @UserSessionRequired
    @GetMapping("/getYahooRefreshTokenByCode")
    @ApiOperation(value = "Yahoo 用户授权第二部 yahoo跳回我们系统 解析url参数 掉此接口 交换用户refreshToken(刷新令牌)", notes = "Yahoo 用户授权第二部 根据上一步返回的 code 交换用户refreshToken(刷新令牌)")
    public SingleResult getYahooRefreshTokenByCode(String code, String state) {
        return SingleResult.success(platformOrderYahooSyncOrderService.getYahooRefreshTokenByCode(code, state, getCurrentUserId(), getCompanyId()));
    }

    @UserSessionRequired
    @GetMapping("/getYahooUserAccessToken")
    @ApiOperation(value = "Yahoo 用户刷新令牌 换取 用户访问令牌", notes = "Yahoo 用户刷新令牌 换取 用户访问令牌")
    public SingleResult getYahooUserAccessToken(Long shopId) {
        return SingleResult.success(platformOrderYahooSyncOrderService.getYahooUserAccessToken(shopId));
    }


    @UserSessionRequired
    @PostMapping("/amazonAuthorizeNow")
    @ApiOperation(value = "亚马逊授权第一步：亚马逊店铺新增/更新授权 掉此接口，跳转到返回的url", notes = "亚马逊店铺新增")
    public SingleResult amazonAuthorizeNow(@RequestBody @Validated StoreAmazonAddReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success(platformOrderAmazonSyncService.authorizeNow(req, userId, getCompanyId()));
    }


    @UserSessionRequired
    @GetMapping("/getAmazonAuthorizeMsg")
    @ApiOperation(value = "亚马逊授权第二步：亚马逊跳回我们系统 解析url参数 掉此接口", notes = "店铺：LWA 授权码交换 LWA 刷新令牌")
    @ApiImplicitParams({@ApiImplicitParam(name = "state", value = "状态码"),
            @ApiImplicitParam(name = "spapi_oauth_code", value = "lwa授权码"),
            @ApiImplicitParam(name = "selling_partner_id", value = "卖家编号(亚马逊)"),
            @ApiImplicitParam(name = "mws_auth_token", value = "MWSAuthToken值")})
    public SingleResult getAmazonAuthorizeMsg(HttpServletRequest request) {
        Long userId = getCurrentUserId();
        Map<String, String> map = new HashMap<>();
        String state = request.getParameter("state");
        String spapi_oauth_code = request.getParameter("spapi_oauth_code");
        String selling_partner_id = request.getParameter("selling_partner_id");
        String mws_auth_token = request.getParameter("mws_auth_token");
        String shopId = request.getParameter("shopId") == null || "".equals(request.getParameter("shopId")) ? "0" : request.getParameter("shopId");

        map.put("state", state);
        map.put("spapi_oauth_code", spapi_oauth_code);
        map.put("selling_partner_id", selling_partner_id);
        map.put("mws_auth_token", mws_auth_token);
        platformOrderAmazonSyncService.getAuthorizeMsg(map, userId, getCompanyId());
        return SingleResult.success("授权成功");
    }


    @UserSessionRequired
    @PostMapping("/rakutenAuth")
    @ApiOperation(value = "乐天店铺授权", notes = "乐天店铺授权")
    public SingleResult rakutenAuth(@RequestBody @Validated StoreRakutenAddReq req) {
        Long userId = getCurrentUserId();
        service.rakutenStoreAdd(req, userId, getCompanyId());
        return SingleResult.success();
    }

    @Deprecated
    @UserSessionRequired
    @PostMapping("/makeshopAuthorizeNow")
    @ApiOperation(value = "Makeshop授权第一步：makeshop店铺新增/更新授权 掉此接口，跳转到返回的url", notes = "Makeshop店铺新增/更新")
    public SingleResult makeshopAuthorizeNow(@RequestBody @Validated StoreMakeshopAddReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success(platformOrderMakeshopSyncService.authorizeNow(req, userId, getCompanyId()));
    }

    @Deprecated
    @UserSessionRequired
    @GetMapping("/getMakeshopAuthorizeMsg")
    @ApiOperation(value = "Makeshop授权第二步：Makeshop跳回我们系统 解析url参数 掉此接口", notes = "Makeshop认证授权")
    public SingleResult getMakeshopAuthorizeMsg(String code, String scope, String state, String error, String error_description) {
        platformOrderMakeshopSyncService.getMakeshopAuthorizeMsg(code, scope, state, error, error_description, getCurrentUserId(), getCompanyId());
        return SingleResult.success("授权成功");
    }

    @UserSessionRequired
    @PostMapping("/makeShopStoreAdd")
    @ApiOperation(value = "MakeShop店铺授权", notes = "MakeShop店铺授权")
    public SingleResult makeShopStoreAdd(@RequestBody @Validated StoreMakeshopAddReq req) {
        service.maekshopStoreAdd(req, getCurrentUserId(), getCompanyId());
        return SingleResult.success("授权成功");
    }

    @UserSessionRequired
    @PostMapping("/qoo10StoreAdd")
    @ApiOperation(value = "Qoo10店铺授权", notes = "Qoo10店铺授权")
    public SingleResult qoo10StoreAdd(@RequestBody @Validated StoreQoo10AddReq req) {
        Long userId = getCurrentUserId();
        service.qoo10StoreAdd(req, userId, getCompanyId());
        return SingleResult.success();
    }


    @UserSessionRequired
    @PostMapping("/shopifyAuthorizeNow")
    @ApiOperation(value = "shopify授权第一步：shopify店铺新增/更新授权 掉此接口，跳转到返回的url", notes = "shopify店铺新增/更新")
    public SingleResult shopifyAuthorizeNow(@RequestBody @Validated StoreShopifyAddReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success(platformOrderShopifySyncOrderService.authorizeNow(req, userId, getCompanyId()));
    }

    @UserSessionRequired
    @GetMapping("/getShopifyAuthorizeMsg")
    @ApiOperation(value = "shopify授权第二步：shopify跳回我们系统 解析url参数 掉此接口", notes = "shopify认证授权")
    public SingleResult getShopifyAuthorizeMsg(String code, String
            session, String state, String host, String hmac, String shop, String timestamp) {
        platformOrderShopifySyncOrderService.getShopifyAuthorizeMsg(getCompanyId(), code, session, state, host, hmac, shop, timestamp, getCurrentUserId());
        return SingleResult.success("授权成功");
    }


    @UserSessionRequired
    @PostMapping("/wowmaAuth")
    @ApiOperation(value = "wowma店铺授权", notes = "wowma店铺授权")
    public SingleResult wowmaAuth(@RequestBody @Validated StoreWowmaAddReq req) {
        Long userId = getCurrentUserId();
        service.wowmaStoreAdd(req, userId, getCompanyId());
        return SingleResult.success();
    }


    @UserSessionRequired
    @GetMapping("/getAboutToExpireStoreList")
    @ApiOperation(value = "获取过期或即将过期店铺", notes = "")
    public SingleResult getAboutToExpireStoreList() {
        List<String> aboutToExpireStoreList = service.getAboutToExpireStoreList(getCurrentUserId(), getCompanyId());
        return SingleResult.success(aboutToExpireStoreList);
    }


}

